<template>
  <div class="submissions-container">
    <h1>作业提交详情</h1>
    
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }}老师</p>
      <router-link to="/teacher/homework">返回作业管理</router-link>
    </div>

    <!-- 作业信息 -->
    <div class="assignment-info" v-if="currentAssignment">
      <h2>{{ currentAssignment.title }}</h2>
      <p>{{ currentAssignment.content }}</p>
      <div class="assignment-meta">
        <span>学科: {{ currentAssignment.subjectName }}</span>
        <span>截止日期: {{ formatDate(currentAssignment.dueDate) }}</span>
        <span>发布时间: {{ formatDate(currentAssignment.createdAt) }}</span>
      </div>
    </div>

    <!-- 提交列表 -->
    <div class="submissions-list">
      <div class="list-header">
        <h2>学生提交情况</h2>
        <button @click="loadSubmissions" class="refresh-btn">刷新</button>
      </div>
      
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="submissions.length > 0" class="submissions-items">
        <div 
          v-for="submission in submissions" 
          :key="submission.id" 
          class="submission-item"
          :class="getStatusClass(submission)"
        >
          <div class="submission-header">
            <h3>{{ submission.studentName }} ({{ submission.studentNumber }})</h3>
            <span :class="getStatusClass(submission)">
              {{ getStatusText(submission) }}
            </span>
          </div>
          <div class="submission-meta">
            <span>提交时间: {{ formatDateTime(submission.submittedAt) }}</span>
          </div>
          <div class="submission-actions">
            <button 
              @click="showSubmissionDetail(submission)"
              class="view-btn"
            >
              查看详情
            </button>
            <button 
              v-if="submission.status === 2" 
              @click="showGradeModal(submission)"
              class="grade-btn"
            >
              批改作业
            </button>
            <button 
              v-if="submission.status === 2" 
              @click="showRejectModal(submission)"
              class="reject-btn"
            >
              退回作业
            </button>
          </div>
        </div>
      </div>
      
      <div v-else class="no-submissions">
        <p>暂无学生提交作业</p>
      </div>
    </div>

    <!-- 查看提交详情模态框 -->
    <div v-if="showDetailModalFlag" class="modal" @click="closeDetailModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>作业提交详情</h2>
          <span class="close" @click="closeDetailModal">&times;</span>
        </div>
        <div class="modal-body">
          <div v-if="currentSubmission">
            <div class="detail-item">
              <label>学生:</label>
              <span>{{ currentSubmission.studentName }} ({{ currentSubmission.studentNumber }})</span>
            </div>
            <div class="detail-item">
              <label>提交内容:</label>
              <div class="submission-content">{{ currentSubmission.content }}</div>
            </div>
            <div v-if="currentSubmission.attachmentUrl" class="detail-item">
              <label>附件:</label>
              <a :href="currentSubmission.attachmentUrl" target="_blank" class="attachment-link">
                查看附件
              </a>
            </div>
            <div class="detail-item">
              <label>提交时间:</label>
              <span>{{ formatDateTime(currentSubmission.submittedAt) }}</span>
            </div>
            <div v-if="currentSubmission.grade" class="detail-item">
              <label>成绩:</label>
              <span>{{ currentSubmission.grade }}</span>
            </div>
            <div v-if="currentSubmission.feedback" class="detail-item">
              <label>教师评语:</label>
              <div class="feedback-content">{{ currentSubmission.feedback }}</div>
            </div>
          </div>
          <div v-else>
            <p>暂无提交信息</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 批改作业模态框 -->
    <div v-if="showGradeModalFlag" class="modal" @click="closeGradeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>批改作业 - {{ selectedSubmission.studentName }}</h2>
          <span class="close" @click="closeGradeModal">&times;</span>
        </div>
        <div class="modal-body">
          <form @submit.prevent="gradeSubmission">
            <div class="form-group">
              <label for="grade">成绩:</label>
              <input 
                type="text" 
                id="grade" 
                v-model="gradeForm.grade" 
                required
                placeholder="请输入成绩"
              />
            </div>
            
            <div class="form-group">
              <label for="feedback">评语:</label>
              <textarea 
                id="feedback" 
                v-model="gradeForm.feedback" 
                required
                placeholder="请输入评语"
                rows="5"
              ></textarea>
            </div>
            
            <div class="form-actions">
              <button type="submit" class="grade-btn">提交评分</button>
              <button type="button" class="cancel-btn" @click="closeGradeModal">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 退回作业模态框 -->
    <div v-if="showRejectModalFlag" class="modal" @click="closeRejectModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>退回作业 - {{ selectedSubmission.studentName }}</h2>
          <span class="close" @click="closeRejectModal">&times;</span>
        </div>
        <div class="modal-body">
          <form @submit.prevent="rejectSubmission">
            <div class="form-group">
              <label for="rejectFeedback">退回原因:</label>
              <textarea 
                id="rejectFeedback" 
                v-model="rejectForm.feedback" 
                required
                placeholder="请输入退回原因"
                rows="5"
              ></textarea>
            </div>
            
            <div class="form-actions">
              <button type="submit" class="reject-btn">确认退回</button>
              <button type="button" class="cancel-btn" @click="closeRejectModal">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>

    <!-- 成功提示 -->
    <div v-if="successMessage" class="success-message">
      {{ successMessage }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

export default {
  name: 'HomeworkSubmissions',
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    const userProfile = ref({});
    const currentAssignment = ref(null);
    const submissions = ref([]);
    const loading = ref(false);
    const errorMessage = ref('');
    const successMessage = ref('');

    // 查看详情相关
    const showDetailModalFlag = ref(false);
    const currentSubmission = ref(null);

    // 批改作业相关
    const showGradeModalFlag = ref(false);
    const selectedSubmission = ref(null);
    const gradeForm = ref({
      grade: '',
      feedback: ''
    });

    // 退回作业相关
    const showRejectModalFlag = ref(false);
    const rejectForm = ref({
      feedback: ''
    });

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          errorMessage.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };

    // 加载作业信息
    const loadAssignmentInfo = async (assignmentId) => {
      try {
        const response = await fetch(`/homework/list/${assignmentId}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1 && result.data.length > 0) {
          currentAssignment.value = result.data[0];
        }
      } catch (err) {
        errorMessage.value = '获取作业信息失败';
      }
    };

    // 加载提交列表
    const loadSubmissions = async () => {
      const assignmentId = route.params.assignmentId;
      if (!assignmentId) return;
      
      try {
        loading.value = true;
        errorMessage.value = '';
        
        const response = await fetch(`/homework/submissions/${assignmentId}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          submissions.value = result.data || [];
        } else {
          errorMessage.value = result.msg || '获取提交列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // 显示提交详情
    const showSubmissionDetail = (submission) => {
      currentSubmission.value = submission;
      showDetailModalFlag.value = true;
    };

    // 关闭详情模态框
    const closeDetailModal = () => {
      showDetailModalFlag.value = false;
      currentSubmission.value = null;
    };

    // 显示批改作业模态框
    const showGradeModal = (submission) => {
      selectedSubmission.value = submission;
      gradeForm.value.grade = '';
      gradeForm.value.feedback = '';
      showGradeModalFlag.value = true;
    };

    // 关闭批改作业模态框
    const closeGradeModal = () => {
      showGradeModalFlag.value = false;
      selectedSubmission.value = null;
    };

    // 批改作业
    const gradeSubmission = async () => {
      try {
        errorMessage.value = '';
        successMessage.value = '';
        
        const response = await fetch(`/homework/grade/${selectedSubmission.value.id}`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams({
            grade: gradeForm.value.grade,
            feedback: gradeForm.value.feedback
          })
        });
        
        const result = await response.json();
        if (result.code === 1) {
          successMessage.value = result.data || '作业批改成功';
          closeGradeModal();
          // 重新加载提交列表以更新状态
          await loadSubmissions();
        } else {
          errorMessage.value = result.msg || '作业批改失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };

    // 显示退回作业模态框
    const showRejectModal = (submission) => {
      selectedSubmission.value = submission;
      rejectForm.value.feedback = '';
      showRejectModalFlag.value = true;
    };

    // 关闭退回作业模态框
    const closeRejectModal = () => {
      showRejectModalFlag.value = false;
      selectedSubmission.value = null;
    };

    // 退回作业
    const rejectSubmission = async () => {
      try {
        errorMessage.value = '';
        successMessage.value = '';
        
        const response = await fetch(`/homework/reject/${selectedSubmission.value.id}`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams({
            feedback: rejectForm.value.feedback
          })
        });
        
        const result = await response.json();
        if (result.code === 1) {
          successMessage.value = result.data || '作业退回成功';
          closeRejectModal();
          // 重新加载提交列表以更新状态
          await loadSubmissions();
        } else {
          errorMessage.value = result.msg || '作业退回失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };

    // 获取状态文本
    const getStatusText = (submission) => {
      switch (submission.status) {
        case 1: return '未完成';
        case 2: return '已提交';
        case 3: return '已批改';
        case 4: return '已退回';
        default: return '未知';
      }
    };

    // 获取状态样式类
    const getStatusClass = (submission) => {
      switch (submission.status) {
        case 1: return 'status-pending';
        case 2: return 'status-submitted';
        case 3: return 'status-graded';
        case 4: return 'status-rejected';
        default: return 'status-unknown';
      }
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    };

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };

    onMounted(() => {
      loadUserProfile();
      const assignmentId = route.params.assignmentId;
      if (assignmentId) {
        loadAssignmentInfo(assignmentId);
        loadSubmissions();
      }
    });

    return {
      userProfile,
      currentAssignment,
      submissions,
      loading,
      errorMessage,
      successMessage,
      showDetailModalFlag,
      currentSubmission,
      showGradeModalFlag,
      selectedSubmission,
      gradeForm,
      showRejectModalFlag,
      rejectForm,
      loadSubmissions,
      showSubmissionDetail,
      closeDetailModal,
      showGradeModal,
      closeGradeModal,
      gradeSubmission,
      showRejectModal,
      closeRejectModal,
      rejectSubmission,
      getStatusText,
      getStatusClass,
      formatDate,
      formatDateTime
    };
  }
};
</script>

<style scoped>
.submissions-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.submissions-container h1 {
  text-align: center;
  color: #333;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info a {
  color: #409EFF;
  text-decoration: none;
}

.user-info a:hover {
  text-decoration: underline;
}

.assignment-info {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.assignment-info h2 {
  margin-top: 0;
  color: #333;
}

.assignment-info p {
  color: #555;
  line-height: 1.5;
  margin-bottom: 15px;
}

.assignment-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #999;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header h2 {
  margin: 0;
  color: #333;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #9E9E9E;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn:hover {
  background-color: #757575;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.submissions-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.submission-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  transition: all 0.3s ease;
}

.submission-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.submission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.submission-header h3 {
  margin: 0;
  color: #333;
}

.submission-meta {
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
}

.submission-actions {
  display: flex;
  gap: 10px;
}

.view-btn, .grade-btn, .reject-btn, .cancel-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.view-btn {
  background-color: #409EFF;
  color: white;
}

.view-btn:hover {
  background-color: #337ecc;
}

.grade-btn {
  background-color: #67C23A;
  color: white;
}

.grade-btn:hover {
  background-color: #55a52a;
}

.reject-btn {
  background-color: #F56C6C;
  color: white;
}

.reject-btn:hover {
  background-color: #e05858;
}

.cancel-btn {
  background-color: #9E9E9E;
  color: white;
}

.cancel-btn:hover {
  background-color: #757575;
}

.no-submissions {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

/* 状态样式 */
.status-pending {
  background-color: #f5f5f5;
  color: #999;
}

.status-submitted {
  background-color: #e8f4fd;
  color: #409EFF;
}

.status-graded {
  background-color: #d4edda;
  color: #67C23A;
}

.status-rejected {
  background-color: #f8d7da;
  color: #f56c6c;
}

.status-unknown {
  background-color: #f5f5f5;
  color: #999;
}

/* 模态框样式 */
.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  border-radius: 5px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  color: #333;
}

.close {
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  color: #999;
}

.close:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #409EFF;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
  color: #555;
}

.submission-content, .feedback-content {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.5;
}

.attachment-link {
  color: #409EFF;
  text-decoration: none;
}

.attachment-link:hover {
  text-decoration: underline;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

@media (max-width: 600px) {
  .assignment-meta {
    flex-direction: column;
    gap: 5px;
  }
  
  .submission-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .submission-actions {
    flex-direction: column;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .modal-content {
    width: 95%;
  }
}
</style>